<?php
/************************
 *  Codenova.pl Project
 *  Created by: Kamil Mrzygłód
 *
 *  (c) 2013 by Codenova.pl
 *  All Right Reserved
 ***********************/

namespace Modules\JasminumGallery\Controllers;

use Gotcha\App\Extensions\GotchaCulturesExtension;
use Gotcha\App\Extensions\GotchaErrorsExtension;
use Gotcha\App\Extensions\GotchaFileSystemExtension;
use Gotcha\App\Extensions\GotchaLogsExtension;
use Gotcha\App\Extensions\HttpExtension;
use Gotcha\App\Framework\Controller;
use Gotcha\App\Types\String;
use GotchaDatabase\GotchaSettings;
use GotchaDatabase\GotchaSettingsQuery;
use GotchaDatabase\JasminumGalleries;
use GotchaDatabase\JasminumGalleriesCategories;
use GotchaDatabase\JasminumGalleriesCategoriesQuery;
use GotchaDatabase\JasminumGalleriesPhotos;
use GotchaDatabase\JasminumGalleriesPhotosQuery;
use GotchaDatabase\JasminumGalleriesQuery;

class AdminController extends Controller {
    private $allowedExtensions = array('jpeg', 'jpg', 'png', 'gif');

    public function Index() {
        return parent::View();
    }

    public function Create() {
        return parent::View();
    }

    public function CreateSubgallery() {
        return parent::View();
    }

    public function CreatePhoto() {
        return parent::View();
    }

    public function CreatePost() {
        $http = new HttpExtension();

        if(empty($_POST['Name']) || !isset($_POST['Name'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/Create?error=1'));
            exit;
        }

        if(is_null($_POST['Description'])) {
            $_POST['Description'] = '';
        }

        // Validate file
        if($_FILES['ImageSrc']['error'] != 0) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/Create?error=2'));
            exit;
        }

        if(isset($_FILES['ImageSrc']['name'])) {
            $file = explode('.', $_FILES['ImageSrc']['name']);
            $fileExtension = end($file);
            if(!in_array($fileExtension, $this->allowedExtensions)) {
                header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/Create?error=3'));
                exit;
            }
        } else {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/Create?error=5'));
            exit;
        }

        if(isset($_FILES['ImageSrc']['size'])) {
            if($_FILES['ImageSrc']['size'] > 1024000) { // More than 10MB
                header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/Create?error=7'));
                exit;
            }
        } else {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/Create?error=6'));
            exit;
        }

        // Check file existence
        $settings = GotchaSettingsQuery::create()
                        ->findOneByStrongName('GalleryThumbnailsDir');
        $thumbnailsDir = $settings->getValue();

        if(GotchaFileSystemExtension::CheckFileExistence(new String($_FILES['ImageSrc']['name']), new String(GOTCHA_ROOT_DIR.$thumbnailsDir)) == true) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/Create?error=8'));
            exit;
        }

        // File passed validation, upload it
        move_uploaded_file($_FILES['ImageSrc']['tmp_name'], GOTCHA_ROOT_DIR.'/Media/JasminumGallery/Thumbnails/'.$_FILES['ImageSrc']['name']);

        // We have to update routing.xml file with the new route
        $xmlFileUrl = GOTCHA_ROOT_DIR.'/App/Routing/routing.xml';
        $xmlData = new \SimpleXMLElement($xmlFileUrl, null, true);
        $route = $xmlData->addChild('route');
        $route->addAttribute('url', '/galeria/'.parent::nameToSlug($_POST['Name']));
        $route->addAttribute('module', 'JasminumGallery');
        $route->addAttribute('controller', 'Default');
        $route->addAttribute('action', 'getGallery');
        $xmlData->saveXML(GOTCHA_ROOT_DIR.'\App\Routing\routing.xml');

        // Add new gallery
        try {
            $gallery = new JasminumGalleries();
            $gallery->setName($_POST['Name']);
            $gallery->setDescription($_POST['Description']);
            $gallery->setImageSrc($_FILES['ImageSrc']['name']);
            $gallery->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery?create=1'));
        exit;
    }

    public function CreatePhotoPost() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_POST['Id']) || !isset($_POST['Id'])) {
            die('Error');
        }

        // Validate file
        if($_FILES['PhotoSrc']['error'] != 0) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/CreatePhoto?error=2&id='.$_POST['Id']));
            exit;
        }

        if(isset($_FILES['PhotoSrc']['name'])) {
            $file = explode('.', $_FILES['PhotoSrc']['name']);
            $fileExtension = end($file);
            if(!in_array($fileExtension, $this->allowedExtensions)) {
                header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/CreatePhoto?error=3&id='.$_POST['Id']));
                exit;
            }
        } else {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/CreatePhoto?error=5&id='.$_POST['Id']));
            exit;
        }

        if(isset($_FILES['PhotoSrc']['size'])) {
            if($_FILES['PhotoSrc']['size'] > 1024000) { // More than 10MB
                header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/CreatePhoto?error=7&id='.$_POST['Id']));
                exit;
            }
        } else {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/CreatePhoto?error=6&id='.$_POST['Id']));
            exit;
        }

        // Check file existence
        $settings = GotchaSettingsQuery::create()
                        ->findOneByStrongName('GalleryMainDir');
        $thumbnailsDir = $settings->getValue();

        if(GotchaFileSystemExtension::CheckFileExistence(new String($_FILES['PhotoSrc']['name']), new String(GOTCHA_ROOT_DIR.$thumbnailsDir)) == true) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/CreatePhoto?error=8&id='.$_POST['Id']));
            exit;
        }

        // File passed validation, upload it
        move_uploaded_file($_FILES['PhotoSrc']['tmp_name'], GOTCHA_ROOT_DIR.'/Media/JasminumGallery/'.$_FILES['PhotoSrc']['name']);

        // Add new photo
        try {
            $photo = new JasminumGalleriesPhotos();
            $photo->setPhotoSrc($_FILES['PhotoSrc']['name']);
            $photo->setJasminumGalleriesCategoriesId($_POST['Id']);
            $photo->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery?create=2'));
        exit;
    }

    public function CreateSubgalleryPost() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_POST['Id']) || !isset($_POST['Id'])) {
            die('Error');
        }

        if(empty($_POST['Name']) ||  !isset($_POST['Name'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/CreateSubgallery?error=1'));
            exit;
        }

        if(is_null($_POST['Description'])) {
            $_POST['Description'] = '';
        }

        // Add new gallery
        try {
            $gallery = new JasminumGalleriesCategories();
            $gallery->setName($_POST['Name']);
            $gallery->setDescription($_POST['Description']);
            $gallery->setJasminumGalleriesId($_POST['Id']);
            $gallery->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery?create=3'));
        exit;
    }

    public function Edit() {
        return parent::View();
    }

    public function EditPost() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_POST['Id']) || !isset($_POST['Id'])) {
            die('Error');
        }

        if(empty($_POST['Name']) || !isset($_POST['Name'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/Edit?error=1&id='.$_POST['Id']));
            exit;
        }

        if(is_null($_POST['Description'])) {
            $_POST['Description'] = '';
        }

        $thumbnail = JasminumGalleriesQuery::create()
                        ->findOneById($_POST['Id'])
                            ->getImageSrc();

        // Check if user chose new thumbnail
        if(isset($_FILES['ImageSrc']['name']) && !empty($_FILES['ImageSrc']['name'])) {
            // Check if it's a  new file
            if($thumbnail != $_FILES['ImageSrc']['name']) {
                // Validate file
                if($_FILES['ImageSrc']['error'] != 0) {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/Edit?error=2&id='.$_POST['Id']));
                    exit;
                }

                if(isset($_FILES['ImageSrc']['name'])) {
                    $fileExtension = end(explode('.', $_FILES['ImageSrc']['name']));
                    if(!in_array($fileExtension, $this->allowedExtensions)) {
                        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/Edit?error=3&id='.$_POST['Id']));
                        exit;
                    }
                } else {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/Edit?error=5&id='.$_POST['Id']));
                    exit;
                }

                if(isset($_FILES['ImageSrc']['size'])) {
                    if($_FILES['ImageSrc']['size'] > 1024000) { // More than 10MB
                        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/Edit?error=7&id='.$_POST['Id']));
                        exit;
                    }
                } else {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/Edit?error=6&id='.$_POST['Id']));
                    exit;
                }

                // Check file existence
                $settings = GotchaSettingsQuery::create()
                    ->findOneByStrongName('GalleryThumbnailsDir');
                $thumbnailsDir = $settings->getValue();

                if(GotchaFileSystemExtension::CheckFileExistence(new String($_FILES['ImageSrc']['name']), new String(GOTCHA_ROOT_DIR.$thumbnailsDir)) == true) {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery/Edit?error=8&id='.$_POST['Id']));
                    exit;
                }

                // File passed validation, upload it
                move_uploaded_file($_FILES['ImageSrc']['tmp_name'], GOTCHA_ROOT_DIR.'/Media/JasminumGallery/Thumbnails/'.$_FILES['ImageSrc']['name']);
            }
        } else {
            $_FILES['ImageSrc']['name'] = $thumbnail;
        }

        // Update routings
        $url = parent::nameToSlug($_POST['OldName']);
        $xmlFileUrl = GOTCHA_ROOT_DIR.'/App/Routing/routing.xml';
        $xmlData = new \SimpleXMLElement($xmlFileUrl, null, true);
        $xmlDataXPath = $xmlData->xpath('//route[@url=\'/galeria/'.$url.'\']');
        $xmlDataXPath[0][0]->attributes()->url = '/galeria/'.parent::nameToSlug($_POST['Name']);
        $xmlData->saveXML($xmlFileUrl);

        // Update
        try {
            JasminumGalleriesQuery::create()
                ->findOneById($_POST['Id'])
                    ->setName($_POST['Name'])
                    ->setDescription($_POST['Description'])
                    ->setImageSrc($_FILES['ImageSrc']['name'])
                        ->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery?edit=1'));
        exit;
    }

    public function Delete() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_GET['id']) || !isset($_GET['id'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery?error=2'));
            exit;
        }

        // Update routings
        $xmlFileUrl = GOTCHA_ROOT_DIR.'\App\Routing\routing.xml';
        $xmlData = new \SimpleXMLElement($xmlFileUrl, null, true);
        $xmlDataXPath = $xmlData->xpath('//route[@url=\''.$_GET['url'].'\']');
        $xmlDataDom = dom_import_simplexml($xmlDataXPath[0]); // DOM import is necessary to delete a node
        $xmlDataDom->parentNode->removeChild($xmlDataDom);
        $xmlData->saveXML($xmlFileUrl);

        // Delete element
        try {
            JasminumGalleriesQuery::create()->findOneById($_GET['id'])->delete();
            JasminumGalleriesCategoriesQuery::create()->filterByJasminumGalleriesId($_GET['id'])->delete();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery'));
        exit;
    }

    public function DeleteSubgallery() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_GET['id']) || !isset($_GET['id'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery?error=2'));
            exit;
        }

        // Delete element
        try {
            JasminumGalleriesCategoriesQuery::create()->findOneById($_GET['id'])->delete();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery'));
        exit;
    }

    public function DeletePhoto() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_GET['id']) || !isset($_GET['id'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery?error=2'));
            exit;
        }

        // Delete element
        try {
            JasminumGalleriesPhotosQuery::create()->findOneById($_GET['id'])->delete();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/Gallery'));
        exit;
    }

    public function returnGalleries() {
        $galleries = JasminumGalleriesQuery::create()
                        ->orderById()
                            ->find();

        $html = '';
        foreach ($galleries as $gallery) {
            $html .= '<tr>';
            $html .= sprintf('<td>%s</td><td>%s</td><td>%s</td><td>[ <a href="%s?id=%s">Edytuj</a> | <a href="%s?id=%s&url=%s" class="delete">Usuń</a> ]</td>', $gallery->getName(), $gallery->getImageSrc(), $gallery->getDescription(), parent::UrlContent('/Admin/Jasminum/Gallery/Edit'), $gallery->getId(), parent::UrlContent('/Admin/Jasminum/Gallery/Delete'), $gallery->getId(), '/galeria/'.parent::nameToSlug($gallery->getName()));
            $html .= '</tr>';
        }

        if($galleries->count() == 0) {
            $html .= '<tr><td colspan="4">Brak dodanych galerii.</td></tr>';
        }

        return $html;
    }

    public function returnGallery($id) {
        $gallery = JasminumGalleriesQuery::create()
                    ->findOneById($id);
        return $gallery;
    }

    public function returnSubgalleries() {
        $galleries = JasminumGalleriesQuery::create()
                        ->orderById()
                            ->find();

        $subgalleries = JasminumGalleriesCategoriesQuery::create()
                            ->find();

        $html = '';

        foreach($galleries as $gallery) {
            $html .= '<tr class="subgalleryName"><td colspan="3">'.$gallery->getName().' [ <a href="'.parent::UrlContent('/Admin/Jasminum/Gallery/CreateSubgallery').'?id='.$gallery->getId().'">Dodaj nową podgalerię</a> ]</td></tr>';

            foreach($subgalleries as $subgallery) {
                if($subgallery->getJasminumGalleriesId() == $gallery->getId()) {
                    $html .= '<tr>';
                    $html .= sprintf('<td>%s</td><td>%s</td><td>[ <a href="%s?id=%s">Edytuj</a> | <a href="%s?id=%s" class="delete">Usuń</a> ]</td>', $subgallery->getName(), $subgallery->getDescription(), parent::UrlContent('/Admin/Jasminum/Gallery/EditSubgallery'), $subgallery->getId(), parent::UrlContent('/Admin/Jasminum/Gallery/DeleteSubgallery'), $subgallery->getId());
                    $html .= '</tr>';
                }
            }
        }

        return $html;
    }

    public function returnGalleriesToSelect() {
        $galleries = JasminumGalleriesQuery::create()
                        ->orderById()
                            ->find();
        if($galleries->count() == 0) {
            return '<p>Brak dodanych galerii.</p>';
        }

        $html = '';
        $html .= '<select name="JasminumGalleryId">';

        foreach($galleries as $gallery) {
            $html .= sprintf('<option value="%s">%s</option>', $gallery->getId(), $gallery->getName());
        }

        $html .= '</select>';
        return $html;
    }

    public function returnPhotos() {
        $galleries = JasminumGalleriesQuery::create()
                        ->orderById()
                            ->find();

        $subgalleries = JasminumGalleriesCategoriesQuery::create()
                            ->orderById()
                                ->find();

        $photos = JasminumGalleriesPhotosQuery::create()
                    ->orderById()
                        ->find();

        $settings = GotchaSettingsQuery::create()
            ->findOneByStrongName('GalleryMainDir');
        $thumbnailsDir = $settings->getValue();

        $html = '';

        foreach($galleries as $gallery) {
            $html .= '<tr class="subgalleryName"><td colspan="2">'.$gallery->getName().'</td></tr>';
            foreach($subgalleries as $subgallery) {
                if($subgallery->getJasminumGalleriesId() == $gallery->getId()) {
                    $html .= '<tr class="subgalleryNamePhotos"><td colspan="2">'.$subgallery->getName().' [ <a href="'.parent::UrlContent('/Admin/Jasminum/Gallery/CreatePhoto').'?id='.$subgallery->getId().'">Dodaj nowe zdjęcie</a> ]</td></tr>';

                    foreach($photos as $photo) {
                        if($photo->getJasminumGalleriesCategoriesId() == $subgallery->getId()) {
                            $html .= '<tr>';
                            $html .= sprintf('<td>%s</td><td>[ <a target="_blank" href="%s">Podgląd</a> | <a href="%s?id=%s" class="delete">Usuń</a> ]</td>', $photo->getPhotoSrc(), parent::UrlContent($thumbnailsDir.$photo->getPhotoSrc()), parent::UrlContent('/Admin/Jasminum/Gallery/DeletePhoto'), $photo->getId());
                            $html .= '</tr>';
                        }
                    }
                }
            }
        }

        return $html;
    }
}